<template>
  <div class="drawer-class">
    <el-drawer v-model="drawer">
      <template #header>
        <p>{{ isUpdate ? '编辑' : '添加' }}用户</p>
      </template>
      <template #default>
        <el-form
          :rules="rules"
          label-width="80px"
          ref="ruleFormRef"
          :model="userFromDate"
        >
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户名"
              v-model="userFromDate.username"
            />
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input
              placeholder="请输入用户昵称"
              v-model="userFromDate.name"
            />
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!isUpdate">
            <el-input
              placeholder="请输入用户密码"
              type="password"
              v-model="userFromDate.password"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="Drawer">
import { addUser, updateUser } from '@/api/acl/user'
import { AclUser } from '@/api/acl/types'
import { computed, reactive, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'

const drawer = ref(false)
const ruleFormRef = ref<FormInstance>()

const open = (row?: AclUser.AddUserReq) => {
  if (row) {
    userFromDate.id = row.id
    userFromDate.username = row.username
    userFromDate.name = row.name
    userFromDate.password = ''
  } else {
    userFromDate.id = undefined
    userFromDate.name = ''
    userFromDate.username = ''
    userFromDate.password = ''
  }

  drawer.value = true
}
const close = () => {
  drawer.value = false
}

defineExpose({
  open,
})

const rules = {
  username: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
}

const userFromDate = reactive<AclUser.AddUserReq>({
  username: '',
  name: '',
  password: '',
})

const emit = defineEmits(['success'])

const submit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (valid) {
      if (isUpdate.value) {
        await updateUser({
          id: userFromDate.id,
          username: userFromDate.username,
          name: userFromDate.name,
        })
      } else {
        await addUser(userFromDate)
      }
    }
  })

  ElMessage.success(`${isUpdate.value ? '修改' : '新增'}'用户成功`)
  close()
  emit('success')
}

const isUpdate = computed(() => !!userFromDate.id)
</script>

<style scoped lang="scss">
.drawer-class :deep(.el-drawer__header) {
  padding: 0 20px;
  font-size: 16px;
}
</style>
